/*
 * DepartmentDetailServlet.java
 * Created on 25. juni 2008, 10:51
 */
package uia.is202.jpademo.web;

import java.io.IOException;
import java.io.PrintWriter;
import javax.persistence.EntityManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import uia.is202.jpademo.data.Department;
import uia.is202.jpademo.data.Employee;



/**
 * DepartmentDetailServlet
 * @author even
 */
public class DepartmentDetailServlet extends AbstractDepartmentServlet {

    
    /**
     * Handle requests. Sends a html page containing the department list.
     *
     * @param req the request object
     * @param resp the response object
     *
     * @throws IOException
     * @throws ServletException
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        EntityManager em = emf.createEntityManager();
        PrintWriter out = response.getWriter();
        
        String tmp;
        Department dep = null;
        tmp = request.getParameter("depno");
        if (tmp != null) {
            long depNo = Long.valueOf(tmp);
            dep = em.find(Department.class, depNo);
        }
        
        response.setContentType("text/html");
        response.setHeader("Cache-control", "no-cache");
        response.setHeader("Expires", "0");

        out.println("<html><head><title>"+this.getClass().getName()+"</title></head><body>");
        out.println("<h1>Department Detail</h1>");
        
        if (dep != null) {
            out.println("<table>");
            printDatum(out, "Name", dep.getName());
            printDatum(out, "Dep.no", dep.getDepNo());
            out.println("</table>");
            out.println("<p><a href=\"depedit?depno="+dep.getDepNo()+"\">Edit department</a></p>");
            out.println("<p><a href=\"depdelete?depno="+dep.getDepNo()+"\">Delete department</a></p>");
            out.println("<h3>Employees</h3>");
            out.println("<table>");
            for (Employee emp : dep.getEmployees()) {
                out.println("<tr><td><a href=\"empdetail?empno="+emp.getEmpNo()+"\">"+emp.getName()+"</a></td></tr>");
            }
            out.println("</table>");
        }
        else out.println("<h1>Dep.no not specified!</h1>");

        out.println("<hr/>");
        out.println("<p><a href=\"index.html\">Home</a> &gt; <a href=\"deplist\">Department List</a></p>");
        out.println("</body>");
        out.println("</html>");
        
        em.close();
    }
}
